/**
 * 
 */
package com.csaba.db.views;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IViewSite;

class UserDBContentProvider implements IStructuredContentProvider, ITreeContentProvider
{
	//private final static Logger logger = LoggerHelper.getDefaultLogger();
	private UserDB[] dbs;

	public UserDBContentProvider()
	{
		loadDBList();
	}

	private void loadDBList()
	{
		final List<UserDB> dbList = new ArrayList<UserDB>();

		//load db list from workspace (practically this is the project list)
		final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		final IProject[] projects = root.getProjects();
		for ( final IProject project : projects )
		{
			dbList.add(new UserDB(project));
		}

		dbs = dbList.toArray(new UserDB[dbList.size()]);
	}

	public void inputChanged( final Viewer v, final Object oldInput, final Object newInput )
	{
	}

	public void dispose()
	{
	}

	public Object[] getElements( final Object parent )
	{
		if ( parent instanceof IViewSite )
		{
			return dbs;
		}

		return getChildren(parent);
	}

	public Object getParent( final Object child )
	{
		if ( child instanceof IUserDBTreeObject )
		{
			return ( (IUserDBTreeObject) child ).getParent();
		}
		return null;
	}

	public Object[] getChildren( final Object parent )
	{
		if ( parent instanceof IUserDBTreeParent )
		{
			return ( (IUserDBTreeParent) parent ).getChildren();
		}
		return new Object[0];
	}

	public boolean hasChildren( final Object parent )
	{
		if ( parent instanceof IUserDBTreeParent )
			return ( (IUserDBTreeParent) parent ).hasChildren();
		return false;
	}

	public void refresh()
	{
		loadDBList();
	}

}